package com.loong.android.http.request;

import com.loong.android.http.RequestEvent;
import com.loong.android.http.response.StringResponse;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.DeleteRequest;
import com.lzy.okgo.request.base.Request;

import java.io.File;
import java.util.Arrays;

/**
 * delete请求类
 */
public class StringDeleteRequest extends DeleteRequest<String> {

    /**
     * 构造方法，初始化delete请求的URL
     * @param url 请求的URL
     */
    public StringDeleteRequest(String url) {
        super(url);
    }

    /**
     * 根据传入的回调事件创建一个StringCallback实例
     * 此方法用于处理请求的生命周期事件，并将事件转发给传入的回调事件
     * @param callback 回调事件，用于处理请求的生命周期事件
     * @return 返回一个实现了请求生命周期方法的StringCallback实例
     */
    private StringCallback listen(RequestEvent.DeleteEvent callback) {
        final StringDeleteRequest req = this;
        return new StringCallback() {
            @Override
            public void onStart(Request<String, ? extends Request> request) {
                super.onStart(request);
                if(callback != null) callback.onStart(req);
            }

            @Override
            public void onSuccess(Response<String> response) {
                if(callback != null) callback.onSuccess(new StringResponse(response));
            }

            @Override
            public void onCacheSuccess(Response<String> response) {
                super.onCacheSuccess(response);
                if(callback != null) callback.onCacheSuccess(new StringResponse(response));
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                if(callback != null) callback.onError(new StringResponse(response));
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if(callback != null) callback.onFinish();
            }
        };
    }

    /**
     * 设置事件回调
     * @param callback 事件回调
     */
    public StringDeleteRequest setCallback(RequestEvent.DeleteEvent callback) {
        super.setCallback(listen(callback));
        return this;
    }

    /**
     * 提交请求
     * @param callback 事件回调
     */
    public StringDeleteRequest execute(RequestEvent.DeleteEvent callback) {
        super.execute(listen(callback));
        return this;
    }

    /**
     * 添加一个key附带多个文件的参数
     * @param key 键名
     * @param files 文件数据数组
     */
    public StringDeleteRequest addFileParams(String key, File[] files) {
        super.addFileParams(key, Arrays.asList(files));
        return this;
    }
}
